import java.io.*;
import java.net.*;
//import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

import db.DatabaseConnector;

public class LogData extends HttpServlet { 
    // doPost method included for POST requests
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        doGet(request, response);
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String tName = "weblog";
        
        // Variables for the database connection
        DatabaseConnector con1 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {       
            // Variables for all of the values we need to insert into the db.
            // Note: the db automatically assigns an ID to a new record.
            String uName = request.getRemoteUser();
            String remote_ip = request.getRemoteAddr();
            String portNum = "" + request.getServerPort();
            String agent = request.getHeader("User-Agent");
            
            // Items from the XHR post
            String url = URLDecoder.decode("" + request.getParameter("_url"), "UTF-8");
            String query_string = "" + URLDecoder.decode("" + request.getParameter("_qs"), "UTF-8");
            String target = "" + request.getParameter("_target");
            String screen = "" + request.getParameter("screenRes");
            
            // If REMOTEUSER is null (i.e. testing), assign the name 'Guest'
            if(uName==null) {
                uName = "Guest  ";
            }

            String SQL = "INSERT INTO " + tName
                    + " (username, remote_ip, url, query_string, target, port, screen, user_agent) VALUES (?,?,?,?,?,?,?,?)";
            con1.freeformSQL(SQL, new Object[]{uName, remote_ip, url, query_string, target, portNum, screen, agent});
        }
        finally
        {
            con1.CleanUp();
        }
    }     
}
